package com.whc.orders.listener;

import com.whc.common.constant.RabbitMqConstant;
import com.whc.common.domain.DelayMessage;
import com.whc.orders.domain.entity.Orders;
import com.whc.orders.mapper.OrdersMapper;
import com.whc.orders.service.OrdersService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;


@Component
@Slf4j
public class RabbitMqListener {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMqConstant.DELAY_ORDER_QUEUE,durable = "true"),
            exchange = @Exchange(name = RabbitMqConstant.DELAY_EXCHANGE,
            delayed = "true"),
            key=RabbitMqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayOrderMessages(DelayMessage<Long> msg){
        log.info("接收到超时订单的延迟消息，开始处理超时订单");
        //检查该订单的状态，是否为已支付
        //这里可以在访问一下支付微服务该订单是否支付(有可能已支付，但未更改，即数据不一致)
        Long orderId = msg.getData();
        Orders orders = ordersMapper.selectById(orderId);

        //已支付或者不存在返回
        if(orders==null||orders.getStatus()==1){
            return;
        }

        //未支付就取消订单
        //是否有剩余的延迟时间
        if(msg.hasNextDelay()){
            //拿到下一个延迟时长
            int time = msg.removeNextDelay().intValue();
            log.info("订单{}发送下一个延迟{}秒的消息",orderId,time);
            rabbitTemplate.convertAndSend(
                    RabbitMqConstant.DELAY_EXCHANGE,RabbitMqConstant.DELAY_ORDER_ROUTING_KEY,
                    msg,message -> {
                        message.getMessageProperties().setDelay(time);
                        return message;
                    }

            );
            return;
        }
        //无就删除订单
        ordersMapper.deleteById(orderId);

        //TODO 远程调用恢复库存

    }

}
